import datetime
import os

import pytz
import rest_framework
from django.http import Http404, JsonResponse
from rest_framework import status
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import generics

from api.ownserializers import SerializerStory, SerializerStoryImg
from common.models import TbStory, TbStoryImg
from travel_guide.settings import BASE_DIR, REST_FRAMEWORK


class StorySingleView(APIView):
    """
    Story的视图集:获取单个的Story对象，上传单个的Story的对象
    """
    def get(self, request, *args, **kwargs):
        """
        处理get请求的视图
        :param request: 请求对象
        :param pk:
        :param args:
        :param kwargs:
        :return: 返回top5数据
        """
        try:
            sid = request.GET.get('sid')
            uid = request.GET.get('uid')
            city = request.GET.get('city')
            if sid:
                ser = SerializerStory(TbStory.objects.filter(id=sid), many=True)
            if uid:
                ser = SerializerStory(TbStory.objects.filter(uid=uid), many=True)
            if city:
                ser = SerializerStory(TbStory.objects.filter(city=city), many=True)
            return Response(ser.data, status=status.HTTP_200_OK)
        except Exception:
            raise Http404

    def search(self, data):
        key = data[0]
        ser = SerializerStory(TbStory.objects.filter(key=data[1]), many=True)
        # img = SerializerStoryImg(TbStoryImg.objects.filter(story_id=pk), many=True)
        return Response(ser.data, status=status.HTTP_200_OK)

    def post(self, request, pk, *args, **kwargs):
        """
        创建故事
        :param self:
        :param request:
        :param pk:
        :param args:
        :param kwargs:
        :return:
        """
        ser = SerializerStory(data=request.data)
        if ser.is_valid():
            ser.save()
        imageid = ser.data['id']
        data = []
        for i in request.FILES:
            filename = request.FILES.get(i).name
            url = os.path.join(BASE_DIR, 'static/')
            url = os.path.join(url, 'story/')
            url = os.path.join(url, f'{imageid}{filename}')
            file = open(url, 'wb+')
            for f in request.FILES.get(i).chunks():
                file.write(f)
            file.close()
            data = {'name': filename, 'url': url, 'story':imageid}
            self.img(data)
        return Response(ser.data, status=status.HTTP_200_OK)

    def img(self, data, *args, **kwargs):
        """保存图片数据"""
        image = SerializerStoryImg(data=data)
        if image.is_valid():
            image.save()


class MyPageNumberPagination(PageNumberPagination):
    page_size = 5
    page_query_param = "page"
    page_size_query_param = "size"


class StoryHotListView(generics.ListCreateAPIView):
    """
    Story的批量读取视图集
    """
    serializer_class = SerializerStory

    def list(self, request, *args, **kwargs):
            pager = MyPageNumberPagination()
            timestr = datetime.datetime.now() - datetime.timedelta(days=7)
            queryset = TbStory.objects.all().filter(create_time__gt=timestr).order_by("views_count")
            paged_query_set = pager.paginate_queryset(
                queryset=queryset, request=request, view=self)
            return pager.get_paginated_response(SerializerStory(paged_query_set, many=True).data, status=status.HTTP_200_OK)


class StoryReadListView(generics.ListCreateAPIView):
    """
    Story的游记列表
    """
    serializer_class = SerializerStory

    def list(self, request, *args, **kwargs):
        timestr = datetime.datetime.now() - datetime.timedelta(days=365)
        queryset = TbStory.objects.all().filter(create_time__gt=timestr).order_by("views_count")
        ser = SerializerStory(queryset, many=True)
        return Response(ser.data, status=status.HTTP_200_OK)


class StoryTravelingListView(generics.ListCreateAPIView):
    """Story的正在旅行的游记"""

    def list(self, request, *args, **kwargs):
        def list(self, request, *args, **kwargs):
            timestr = datetime.datetime.now() - datetime.timedelta(days=7)
            queryset = TbStory.objects.all().filter(create_time__gt=timestr).order_by("-create_time")
            ser = SerializerStory(queryset, many=True)
            return Response(ser.data, status=status.HTTP_200_OK)